import React, {Component, Fragment} from 'react'
import {connect} from 'react-redux'
import {Link, withRouter} from 'react-router-dom'
import { List, Avatar, Button, message } from 'antd'
import UserRouter from '../index'
import {dropRepeat, fromNow, http, notLogin, post, filterText, queryParse} from '../../../common/js/utils'
import {Page} from '../../../component/pagination'
import './style.scss'
import {ReplyForm} from '../../detail/reply_form'
import {GoodIcon} from './good_icon'
import {PopConfirm} from '../../../component/pop_confirm'

function mapStateToProps(state, props) {
  return {
    userInfo: state.get('userInfo')
  }
}

@connect(mapStateToProps)
@withRouter
class CommentRouter extends Component {

  state = {
    loading: false,
    list: [],
    total: 0
  }

  page = 0
  size = 5

  replySuccess = (item, comment) => {
    comment.replies.unshift(item)
    comment.reply_count++
    const {list} = this.state
    this.setState({list})
  }

  getList = () => {
    http({
      method: 'get',
      url: `/api/users/myComments?page=${this.page}&size=${this.size}&_id=${this.search._id || ''}`
    }, loading => {
      this.setState({loading})
    }).then(res => {
      if (res.result === 1) {
        let list = res.data
        this.setState({list, total: res.total})
      }
    }).catch(err => console.log(err))
  }

  componentWillMount() {
    this.search = queryParse(this.props.location.search)
    this.getList()
  }

  like = (item, key) => {
    if (this.props.userInfo.get('status') !== 1) {
      notLogin()
      return
    }
    if (this.goodLoading) return
    this.goodLoading = true
    post('/api/comments/good', {
      commentId: item._id
    }).then(res => {
      this.goodLoading = false
      if (res.result === 1) {
        let list = this.state.list
        list[key].clicked = !list[key].clicked
        if (list[key].clicked) {
          list[key].good_count++
        } else {
          list[key].good_count--
        }
        this.setState({list})
      }
    }).catch(err => {
      this.goodLoading = false
    })
  }

  goodReply = (it, k, key) => {
    if (this.props.userInfo.get('status') !== 1) {
      notLogin()
      return
    }
    post('/api/reply/good', {
      replyId: it._id
    }).then(res => {
      if (res.result === 1) {
        const comments = this.state.list
        comments[key].replies[k].clicked = !comments[key].replies[k].clicked
        if (comments[key].replies[k].clicked) {
          comments[key].replies[k].good_count++
        } else {
          comments[key].replies[k].good_count--
        }
        this.setState({list: comments})
      }
    })
  }

  moreReplies = (item, key, page) => {
    page = item.repliesPage || (item.repliesPage = 0)
    const comments = this.state.list
    http({
      method: 'get',
      url: `/api/reply/list?commentId=${item._id}&page=${page}&size=10`
    }).then(res => {
      if (item.repliesPage === 0) item.replies = []
      item.replies = item.replies.concat(res.data)
      item.replies = dropRepeat(a => a._id)(item.replies)
      item.reply_count = res.total
      item.repliesPage = res.page
      comments.splice(key, 1, item)
      this.setState({comments})
    })
  }

  delReply = (it, k, key) => {
    if (this.props.userInfo.get('status') !== 1) {
      notLogin()
      return
    }
    post('/api/reply/del', {
      replyId: it._id
    }).then(res => {
      if (res.result === 1) {
        const comments = this.state.list
        comments[key].reply_count--
        comments[key].replies.splice(k, 1)
        this.setState({list: comments})
      }
    })
  }

  removeComment = (item) => {
    post('/api/comments/remove', {
      commentId: item._id
    }).then(res => {
      if (res.result === 1) {
        message.success('删除成功')
        this.getList()
      }
    })
  }

  render() {
    let {loading, list, total} = this.state
    const {userInfo: loginUser} = this.props

    return (
      <UserRouter>
        <List
          loading={loading}
          itemLayout="vertical"
          dataSource={list}
          className="user-comments"
          renderItem={(item, key) => (
            <Fragment>
              <List.Item
                className="common-item"
                key={item._id}
                actions={[
                  <GoodIcon title={`${item.good_count}人觉得很赞`} onClick={e => this.like(item, key)} type="like-o" text={item.good_count} clicked={item.clicked} />,
                  <GoodIcon title={`${item.reply_count}条回复`} type="message" text={item.reply_count} />,
                  <PopConfirm
                    onConfirm={e => this.removeComment(item)}
                  >
                    {
                      loginUser.get('_id') === item.createdBy._id ?
                        <Button
                          type="link"
                          style={{
                            color: '#ff4d4f',
                            padding: '0 0'
                          }}
                        >删除</Button> :
                        <ReplyForm
                          comment={item}
                          onSuccess={e => this.replySuccess(e, item)}
                        >
                          <Button type="link" title={`回复“${item.createdBy.nickname}”`} className="edit" >回复</Button>
                        </ReplyForm>
                    }

                  </PopConfirm>
                ]}
                extra={
                  <Link to={`/detail/${item.movie._id}`}>
                    <img width={100} alt="logo" src={item.movie.poster} title={item.movie.title} />
                  </Link>
                }
              >
                <List.Item.Meta
                  avatar={<Avatar src={item.createdBy.face} title={item.createdBy.nickname} />}
                  title={
                    <span
                      style={{
                        fontSize: 12,
                        color: '#666',
                        fontWeight: 'normal'
                      }}
                    >{fromNow(item.meta.createdAt)}</span>
                  }
                />
                <div
                  style={{
                    padding: '0 0 0 10px'
                  }}
                  dangerouslySetInnerHTML={{__html: filterText(item.content)}}
                />
              </List.Item>
              {
                item.replies.map((it, k) => (
                  <List.Item
                    key={it._id}
                    className="common-item"
                    style={{
                      padding: '10px 0 10px 30px'
                    }}
                  >
                    <List.Item.Meta
                      style={{
                        marginBottom: 0
                      }}
                      avatar={<Avatar src={it.createdBy.face} title={it.createdBy.nickname} />}
                      title={
                        <div className="reply-item">
                          <div>
                            <span
                              style={{
                                fontSize: 14
                              }}
                            >{it.createdBy.nickname}</span>
                            <span
                              style={{
                                fontSize: 12,
                                fontWeight: 'normal',
                                marginLeft: 8,
                                color: '#666'
                              }}
                            >{fromNow(it.meta.createdAt)}</span>
                            {
                              loginUser.get('_id') === it.createdBy._id ?
                                <PopConfirm
                                  onConfirm={e => this.delReply(it, k, key)}
                                >
                                  <Button
                                    title="删除"
                                    className="edit danger"
                                    type="link"
                                  >删除</Button>
                                </PopConfirm> :
                                <ReplyForm
                                  comment={item}
                                  reply={it}
                                  onSuccess={e => this.replySuccess(e, item)}
                                >
                                  <Button type="link" title={`回复“${it.createdBy.nickname}”`} className="edit" >回复</Button>
                                </ReplyForm>
                            }
                          </div>
                          <GoodIcon title={`${it.good_count}人觉得很赞`} onClick={e => this.goodReply(it, k, key)} type="like-o" text={it.good_count} clicked={it.clicked} />
                        </div>
                      }
                      description={
                        <div>
                          {
                            it.at ?
                              <p className="reply-at">
                                回复&nbsp;@<span>{it.replyTo.nickname}</span>：
                                <span dangerouslySetInnerHTML={{__html: filterText(it.at.content)}} />
                              </p> :
                              null
                          }
                          <p className="reply-content" dangerouslySetInnerHTML={{__html: filterText(it.content)}} />
                        </div>
                      }
                    />
                  </List.Item>
                ))
              }
              {
                item.replies.length >= item.reply_count ?
                  null :
                  <div
                    style={{
                      textAlign: 'center'
                    }}
                  >
                    <Button
                      type="link"
                      onClick={e => {
                        item.repliesPage++
                        this.moreReplies(item, key)
                      }}
                    >查看更多回复</Button>
                  </div>
              }
            </Fragment>
          )}
        />
        <Page
          total={total}
          size={this.size}
          showSizeChanger={false}
          onChange={(page, size) => {
            this.page = page - 1
            this.getList()
          }}
        />
      </UserRouter>
    )
  }
}

export default CommentRouter